/**
 * Created by tdzl2_000 on 2016-01-24.
 */

import React from 'react';
import {
  BackAndroid,
  Navigator,
  AppState,
  StyleSheet,
  View,
  Platform,
} from 'react-native';
import dismissKeyboard from 'react-native/Libraries/Utilities/dismissKeyboard';

import NavigatorProvider from './components/NavigatorProvider';
import RouterContainer from './components/RouterContainer';

import { DefaultSceneConfig } from './SceneConfig';

import Subscribe from './components/Subscribe';
import RPC, { clearToken } from './logics/rpc';

import { routeConfig } from './pages';

const INITIAL_ROUTE = {
  location: '/splash',
};

const styles = StyleSheet.create({
  root: {
    flex: 1,
  },
  navigator: {
  },
});

export default class App extends React.Component {
  componentWillMount() {
    if (Platform.OS === 'android') {
      BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
    this.lastAppState = AppState.currentState;
    AppState.addEventListener('change', this.onAppStateChange);
  }

  componentDidMount() {
    this.refs.navigator.navigationContext.addListener('willfocus', this.onNavigatorWillFocus);
  }

  componentWillUnmount() {
    if (Platform.OS === 'android') {
      BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
    AppState.removeEventListener('change', this.onAppStateChange);
    this.refs.navigator.navigationContext.removeListener('willfocus', this.onNavigatorWillFocus);
  }

  // 当服务器返回token失效的时候,跳转到登录界面
  onInvalidToken = () => {
    const { navigator } = this.refs;
    if (navigator) {
      clearToken();
      navigator.immediatelyResetRouteStack([{
        location: '/login',
      }]);
    }
  };

  // 切换页面时隐藏键盘
  onNavigatorWillFocus = () => {
    dismissKeyboard();
  };

  // 应用从后台返回时隐藏键盘
  onAppStateChange = state => {
    if (state === 'active' && this.lastAppState !== 'active') {
      dismissKeyboard();
    }
    this.lastAppState = state;
  };

  // 按下back键的处理
  onBackAndroid = () => {
    const nav = this.refs.navigator;
    const routers = nav.getCurrentRoutes();

    if (routers.length > 1) {
      // 当按下back键时回退到上一页面
      nav.pop();
    }

    return true;
  };

  // 配置路由切换动画
  configureScene = (route) => {
    // 根据路由选择指定的场景配置
    if (route && route.sceneConfig) {
      return route.sceneConfig;
    }
    return DefaultSceneConfig;
  };

  // 渲染场景
  renderScene = (route, navigator) => {
    if (!route) {
      return null;
    }
    if (route.location) {
      // 通过location渲染页面
      return (
        <NavigatorProvider navigator={navigator}>
          <RouterContainer
            routeConfig={routeConfig}
            route={route}
            passProps={route.passProps}
            location={route.location}
          />
        </NavigatorProvider>
      );
    } else if (route.component) {
      // 通过component渲染页面,用于Dialog等场景
      const Component = route.component;
      return (
        <NavigatorProvider navigator={navigator}>
          <Component {...route.passProps} />
        </NavigatorProvider>
      );
    }
    return null;
  };

  render() {
    return (
      <View style={styles.root}>
        <Subscribe target={RPC} eventName="invalidToken" listener={this.onInvalidToken} />
        {/* <StatusBar translucent barStyle="light-content" /> */}
        <Navigator
          configureScene={this.configureScene}
          initialRoute={INITIAL_ROUTE}
          style={styles.navigator}
          ref="navigator"
          renderScene={this.renderScene}
        />
      </View>
    );
  }
}
